/**
 * @author 0283000115
 * @date 2018年3月3日-下午2:32:37
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zte.claa.inficombo.csa.app.controller.ret.ApiResult;
import com.zte.claa.inficombo.csa.app.model.dev.DevBase;
import com.zte.claa.inficombo.csa.app.model.redis.AlarmData;
import com.zte.claa.inficombo.csa.app.service.csa.impl.BaseCacheManager;
import com.zte.claa.inficombo.csa.app.service.rptparse.ext.fengyu.FengYuParseResult;
import com.zte.claa.inficombo.csa.app.service.rptparse.ext.fengyu.FengYuParserService;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;

import io.swagger.annotations.ApiOperation;

/**
 * @author 0283000115
 * 
 * 该controller仅用于接收上海枫煜电气火灾的解析结果数据.
 *
 */

@RestController
public class FengYuApiController extends BaseController {
	public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	// logger
	private Logger logger = LoggerFactory.getLogger(FengYuApiController.class);
	
	@Autowired 
	private FengYuParserService fengYuService;
	
	@Autowired
	private BaseCacheManager cacheManager;

    /**
     * 枫煜电气火灾测量数据推送
     * 
     * @param request
     * @return 
     * @throws Exception
     * 
     * HttpServletRequest request, HttpSession session
     * 
     * 采集预警装置信息 http://180.169.39.225:9908/dev-status
     *  sensor_no	装置no	18	0	== deveui
		create_time	时间		0	    == yyyy-MM-dd HH:mm:ss
		port1	测点温度1	10	1	℃
		port2	环境温度	10	1	℃
		port3	测点温度2	10	1	℃
		port4	湿度		10	1	RH
		port5	烟雾		10	1	PPM
		port6	电流		10	1	A

     */
	@ApiOperation(value = "设备数据推送", notes = "枫煜电气火灾测量数据推送")
	@RequestMapping(value={"/dev-status"})
	@ResponseBody
	public ApiResult<?> devDataRpt(HttpServletRequest request) throws Exception{		
		String devEui = request.getParameter("sensor_no");
		String collectTime = request.getParameter("create_time");
		String tempt1 = request.getParameter("port1");
		String temptenv = request.getParameter("port2");
		String tempt2 = request.getParameter("port3");
		String humd = request.getParameter("port4");
		String smoke = request.getParameter("port5");
		String electric = request.getParameter("port6");
		if(devEui == null || devEui.trim().equals("")){
			String jsonStr = this.getJsonParam(request);
			JSONObject json = new JSONObject(jsonStr);
			devEui = JsonUtils.getJsonAttrVal(json, "sensor_no", null);
			collectTime = JsonUtils.getJsonAttrVal(json, "create_time", "");
			tempt1 = JsonUtils.getJsonAttrVal(json, "port1", "0");
			temptenv = JsonUtils.getJsonAttrVal(json, "port2", "0");
			tempt2 = JsonUtils.getJsonAttrVal(json, "port3", "0");
			humd = JsonUtils.getJsonAttrVal(json, "port4", "0");
			smoke = JsonUtils.getJsonAttrVal(json, "port5", "0");
			electric = JsonUtils.getJsonAttrVal(json, "port6", "0");
		}		
		devEui = (devEui == null) ? "" : devEui.trim();
		collectTime = (collectTime == null) ? "" : collectTime.trim();
		logger.info("devDataRpt: devEui="+devEui+", collectTime="+collectTime+
				    ", tempt1="+tempt1+", temptenv="+temptenv+", tempt2="+tempt2+
				    ", humd="+humd+", smoke="+smoke+", electric="+electric);
		tempt1 = (tempt1 == null || tempt1.trim().equals("")) ? "0" : tempt1.trim();
		temptenv = (temptenv == null || temptenv.trim().equals("")) ? "0" : temptenv.trim();
		tempt2 = (tempt2 == null || tempt2.trim().equals("")) ? "0" : tempt2.trim();
		humd = (humd == null || humd.trim().equals("")) ? "0" : humd.trim();
		smoke = (smoke == null || smoke.trim().equals("")) ? "0" : smoke.trim();
		electric = (electric == null || electric.trim().equals("")) ? "0" : electric.trim();
		// 提交数据.
		FengYuParseResult parseData = new FengYuParseResult();
		parseData.setCreatetime(collectTime);
		parseData.setSensorno(devEui);
		parseData.setCurrent(Double.parseDouble(electric));
		parseData.setEnvtemp(Double.parseDouble(temptenv));
		parseData.setHumd(Double.parseDouble(humd));
		parseData.setMptemp1(Double.parseDouble(tempt1));
		parseData.setMptemp2(Double.parseDouble(tempt2));
		parseData.setSm(Double.parseDouble(smoke));
		this.fengYuService.onParseMeteDataReceive(parseData);
		ApiResult<String> ret = new ApiResult<String>();
		ret.setData("");
		ret.setRemark("success");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}
	
	/**
	 * dev-alarm 
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 * 
	    sensor_no	装置no	18	
		create_time	时间		
		threshold_id	报警状态	1	正常= ‘0’
		提醒=‘1’
		注意=‘2’
		危急=‘3’
	 */
	@ApiOperation(value = "设备告警上报", notes = "枫煜电气火灾告警推送")
	@RequestMapping(value={"/dev-alarm"})
	@ResponseBody
	public ApiResult<?> devAlarmRpt(HttpServletRequest request) throws Exception{	
		ApiResult<String> ret = new ApiResult<String>();
		String devEui = request.getParameter("sensor_no");
		String collectTime = request.getParameter("create_time");
		String thresholdid = request.getParameter("threshold_id");
		if(devEui == null || devEui.trim().equals("")){
			String jsonStr = this.getJsonParam(request);
			JSONObject json = new JSONObject(jsonStr);
			devEui = JsonUtils.getJsonAttrVal(json, "sensor_no", null);
			collectTime = JsonUtils.getJsonAttrVal(json, "create_time", "");
			thresholdid = JsonUtils.getJsonAttrVal(json, "threshold_id", "0");
		}
		devEui = (devEui == null) ? "" : devEui.trim();
		logger.info("devAlarmRpt: devEui="+devEui+", collectTime="+collectTime+", thresholdid="+thresholdid);
		thresholdid = (thresholdid == null || thresholdid.trim().equals("")) ? "0" : thresholdid.trim();
		DevBase dev = this.cacheManager.getDev(devEui);
		if(dev == null){
			logger.error("[*@@*]Can not get dev data for sensor: "+devEui);
			ret.setData(devEui);
			ret.setRemark("Sensor not exist!");
			ret.setResult(ApiResult.RET_FAIL);		
			return ret;
		}
		Timestamp alarmTime = new Timestamp(System.currentTimeMillis());
		try{
			SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
			alarmTime = new Timestamp(sdf.parse(collectTime).getTime());	
		}catch(Exception ignore){
			logger.warn(ignore.getMessage(), ignore);
		}
		int alarmcodeFlag = Integer.parseInt(thresholdid);
		AlarmData alarm = new AlarmData();
		alarm.setAlarmcode(thresholdid);
		alarm.setAlarmlevel(AlarmData.ALARM_LEVEL_1);
		alarm.setAlarmtime(alarmTime);
		alarm.setConfirmer("");
		alarm.setConfirmstate(AlarmData.CONFIRM_STATE_N);
		alarm.setDescp(this.getAlarmTitle(alarmcodeFlag)+"["+alarmcodeFlag+"]");
		alarm.setDeveui(devEui);
		alarm.setDevtype(dev.getDevType());
		alarm.setProjectid(dev.getProjectId());
		alarm.setTitle(this.getAlarmTitle(alarmcodeFlag));
		alarm.setRemark("");
		alarm.setTypeflag(this.getAlarmTypeFlag(alarmcodeFlag));
		this.fengYuService.onParseAlarmReceive(alarm);
		ret.setData("");
		ret.setRemark("success");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}
	
	/**
	 * 报警状态:
		                    正常= ‘0’
				提醒=‘1’
				注意=‘2’
				危急=‘3’
	 * @param alarmcodeFlag
	 * @return
	 */
	private String getAlarmTitle(int alarmcodeFlag){
		String alarmTitle = "其他状态";
		switch(alarmcodeFlag){
		case 0: 
			alarmTitle = "正常状态";
			break;
		case 1: 
			alarmTitle = "提醒状态";
			break;
		case 2: 
			alarmTitle = "注意状态";
			break;
		case 3: 
			alarmTitle = "危急状态";
			break;
		}
		return alarmTitle;
	}
	
	private byte getAlarmTypeFlag(int alarmcodeFlag){
		if(alarmcodeFlag == 0){
			return AlarmData.TPFLAG_CLEAR;
		}
		return AlarmData.TPFLAG_ALARM;
	}
	
	/**
	 * dev-install
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 * 
	 *  sensor_no	装置no	18
		sensor_address	安装地址	512
	 */
	@ApiOperation(value = "设备位置上报", notes = "枫煜电气火灾安装位置推送")
	@RequestMapping(value={"/dev-install"})
	@ResponseBody
	public ApiResult<?> devInstallAddrRpt(HttpServletRequest request) throws Exception{		
		String devEui = request.getParameter("sensor_no");
		String devAdrr = request.getParameter("sensor_address");
		if(devEui == null || devEui.trim().equals("")){
			String jsonStr = this.getJsonParam(request);
			JSONObject json = new JSONObject(jsonStr);
			devEui = JsonUtils.getJsonAttrVal(json, "sensor_no", null);
			devAdrr = JsonUtils.getJsonAttrVal(json, "sensor_address", "");
		}
		devEui = (devEui == null) ? "" : devEui.trim();
		logger.info("devInstallAddrRpt: devEui="+devEui+", devAdrr="+devAdrr);
		// 暂时不做dev地址修改...
		this.fengYuService.onParseDevAddrReceive(devEui, devAdrr);
		ApiResult<String> ret = new ApiResult<String>();
		ret.setData(devEui);
		ret.setRemark("success");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}
	
	/**
	 * 后门方法，关闭链路.
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "关闭到枫煜服务器的链路", notes = "关闭到枫煜服务器的链路")
	@RequestMapping(value={"/closeconn2svr"})
	@ResponseBody
	public ApiResult<?> closeconn2svr(HttpServletRequest request) throws Exception{		
		ApiResult<String> ret = new ApiResult<String>();
		String token = request.getParameter("token");
		if(token == null || !token.equals("Claa2017")){
			ret.setData("");
			ret.setRemark("token不正确！");
			ret.setResult(ApiResult.RET_FAIL);		
			return ret;
		}
		this.fengYuService.closeConnectionToDestSvr();
		ret.setData("");
		ret.setRemark("success");
		ret.setResult(ApiResult.RET_SUCC);		
		return ret;
	}
	
}
